package com.cb.admin.controllers;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.cb.admin.domain.UserInfo;

/**
 * Base
 * @author Administrator
 *
 */
public class BaseController{
	
	/**
	 * 获取session的值
	 * @param session
	 * @return
	 */
	public UserInfo returnSessionObj(HttpSession session){
		//初始化对象
		Subject subject = SecurityUtils.getSubject();
		return (UserInfo) subject.getPrincipal();
	}
	
	/**
     * 根据名字获取cookie
     * @param request
     * @param name cookie名字
     * @return
     */
    public Cookie getCookieByName(HttpServletRequest request,String name){
        Map<String,Cookie> cookieMap = ReadCookieMap(request);
        if(cookieMap.containsKey(name)){
            Cookie cookie = (Cookie)cookieMap.get(name);
            return cookie;
        }else{
            return null;
        }   
    }
      
    /**
     * 添加Cookie
     * @param response
     * @param name
     * @param value
     */
    public void addCookie(HttpServletResponse response,String name,String value){
        Cookie cookie = new Cookie(name.trim(), value.trim());
        cookie.setPath("/");
        response.addCookie(cookie);
    }  
      
    /**
     * 将cookie封装到Map里面
     * @param request
     * @return
     */
    private  Map<String,Cookie> ReadCookieMap(HttpServletRequest request){  
        Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
}
